// 游戏常量
const GRID_SIZE = 20; // 网格大小
const GRID_COUNT = 20; // 网格数量
const GAME_SPEED = 150; // 游戏速度（毫秒）

// 方向常量
const DIRECTIONS = {
    UP: { x: 0, y: -1 },
    DOWN: { x: 0, y: 1 },
    LEFT: { x: -1, y: 0 },
    RIGHT: { x: 1, y: 0 }
};

// 获取DOM元素
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const startButton = document.getElementById('start-btn');
const pauseButton = document.getElementById('pause-btn');
const restartButton = document.getElementById('restart-btn');

// 游戏状态
let snake = [];
let food = {};
let direction = DIRECTIONS.RIGHT;
let nextDirection = DIRECTIONS.RIGHT;
let score = 0;
let gameInterval = null;
let isPaused = false;
let isGameOver = true;

// 初始化游戏
function initGame() {
    // 初始化蛇
    snake = [
        { x: 5, y: 10 },
        { x: 4, y: 10 },
        { x: 3, y: 10 }
    ];
    
    // 设置初始方向
    direction = DIRECTIONS.RIGHT;
    nextDirection = DIRECTIONS.RIGHT;
    
    // 重置分数
    score = 0;
    scoreElement.textContent = score;
    
    // 生成食物
    generateFood();
    
    // 重置游戏状态
    isPaused = false;
    isGameOver = false;
    
    // 更新按钮状态
    startButton.disabled = true;
    pauseButton.disabled = false;
    restartButton.disabled = false;
    
    // 清除之前的游戏循环
    if (gameInterval) {
        clearInterval(gameInterval);
    }
    
    // 开始游戏循环
    gameInterval = setInterval(gameLoop, GAME_SPEED);
    
    // 绘制初始状态
    draw();
}

// 游戏主循环
function gameLoop() {
    if (isPaused || isGameOver) return;
    
    // 更新方向
    direction = nextDirection;
    
    // 移动蛇
    moveSnake();
    
    // 检查碰撞
    if (checkCollision()) {
        gameOver();
        return;
    }
    
    // 检查是否吃到食物
    if (snake[0].x === food.x && snake[0].y === food.y) {
        eatFood();
    }
    
    // 绘制游戏
    draw();
}

// 移动蛇
function moveSnake() {
    // 获取蛇头
    const head = { x: snake[0].x, y: snake[0].y };
    
    // 根据方向移动蛇头
    head.x += direction.x;
    head.y += direction.y;
    
    // 将新蛇头添加到蛇身前面
    snake.unshift(head);
    
    // 如果没有吃到食物，移除蛇尾
    if (!(head.x === food.x && head.y === food.y)) {
        snake.pop();
    }
}

// 检查碰撞
function checkCollision() {
    const head = snake[0];
    
    // 检查是否撞墙
    if (head.x < 0 || head.x >= GRID_COUNT || head.y < 0 || head.y >= GRID_COUNT) {
        return true;
    }
    
    // 检查是否撞到自己（从第二个身体部分开始检查）
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            return true;
        }
    }
    
    return false;
}

// 生成食物
function generateFood() {
    // 随机生成食物位置
    let newFood;
    let foodOnSnake;
    
    do {
        foodOnSnake = false;
        newFood = {
            x: Math.floor(Math.random() * GRID_COUNT),
            y: Math.floor(Math.random() * GRID_COUNT)
        };
        
        // 检查食物是否生成在蛇身上
        for (let i = 0; i < snake.length; i++) {
            if (newFood.x === snake[i].x && newFood.y === snake[i].y) {
                foodOnSnake = true;
                break;
            }
        }
    } while (foodOnSnake);
    
    food = newFood;
}

// 吃食物
function eatFood() {
    // 增加分数
    score += 10;
    scoreElement.textContent = score;
    
    // 生成新食物
    generateFood();
    
    // 每得到50分增加游戏速度
    if (score % 50 === 0) {
        clearInterval(gameInterval);
        gameInterval = setInterval(gameLoop, Math.max(50, GAME_SPEED - Math.floor(score / 50) * 10));
    }
}

// 游戏结束
function gameOver() {
    isGameOver = true;
    clearInterval(gameInterval);
    startButton.disabled = false;
    pauseButton.disabled = true;
    
    // 绘制游戏结束提示
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.font = '30px Arial';
    ctx.fillStyle = 'white';
    ctx.textAlign = 'center';
    ctx.fillText('游戏结束', canvas.width / 2, canvas.height / 2 - 30);
    
    ctx.font = '20px Arial';
    ctx.fillText(`最终得分: ${score}`, canvas.width / 2, canvas.height / 2 + 10);
    ctx.fillText('按"开始游戏"重新开始', canvas.width / 2, canvas.height / 2 + 40);
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制背景网格
    drawGrid();
    
    // 绘制蛇
    drawSnake();
    
    // 绘制食物
    drawFood();
}

// 绘制网格
function drawGrid() {
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 0.5;
    
    // 绘制垂直线
    for (let i = 0; i <= GRID_COUNT; i++) {
        ctx.beginPath();
        ctx.moveTo(i * GRID_SIZE, 0);
        ctx.lineTo(i * GRID_SIZE, canvas.height);
        ctx.stroke();
    }
    
    // 绘制水平线
    for (let i = 0; i <= GRID_COUNT; i++) {
        ctx.beginPath();
        ctx.moveTo(0, i * GRID_SIZE);
        ctx.lineTo(canvas.width, i * GRID_SIZE);
        ctx.stroke();
    }
}

// 绘制蛇
function drawSnake() {
    snake.forEach((segment, index) => {
        // 蛇头和蛇身使用不同颜色
        if (index === 0) {
            ctx.fillStyle = '#4CAF50'; // 蛇头颜色
        } else {
            // 为蛇身创建渐变色
            const greenValue = Math.max(50, 150 - index * 3);
            ctx.fillStyle = `rgb(76, ${greenValue}, 80)`;
        }
        
        // 绘制圆角矩形作为蛇的身体部分
        roundRect(
            ctx,
            segment.x * GRID_SIZE + 1,
            segment.y * GRID_SIZE + 1,
            GRID_SIZE - 2,
            GRID_SIZE - 2,
            5
        );
        
        // 为蛇头添加眼睛
        if (index === 0) {
            // 根据方向确定眼睛位置
            const eyeSize = 3;
            let eyeX1, eyeY1, eyeX2, eyeY2;
            
            if (direction === DIRECTIONS.RIGHT) {
                eyeX1 = segment.x * GRID_SIZE + GRID_SIZE - 6;
                eyeY1 = segment.y * GRID_SIZE + 5;
                eyeX2 = segment.x * GRID_SIZE + GRID_SIZE - 6;
                eyeY2 = segment.y * GRID_SIZE + GRID_SIZE - 8;
            } else if (direction === DIRECTIONS.LEFT) {
                eyeX1 = segment.x * GRID_SIZE + 5;
                eyeY1 = segment.y * GRID_SIZE + 5;
                eyeX2 = segment.x * GRID_SIZE + 5;
                eyeY2 = segment.y * GRID_SIZE + GRID_SIZE - 8;
            } else if (direction === DIRECTIONS.UP) {
                eyeX1 = segment.x * GRID_SIZE + 5;
                eyeY1 = segment.y * GRID_SIZE + 5;
                eyeX2 = segment.x * GRID_SIZE + GRID_SIZE - 8;
                eyeY2 = segment.y * GRID_SIZE + 5;
            } else if (direction === DIRECTIONS.DOWN) {
                eyeX1 = segment.x * GRID_SIZE + 5;
                eyeY1 = segment.y * GRID_SIZE + GRID_SIZE - 6;
                eyeX2 = segment.x * GRID_SIZE + GRID_SIZE - 8;
                eyeY2 = segment.y * GRID_SIZE + GRID_SIZE - 6;
            }
            
            // 绘制眼睛
            ctx.fillStyle = 'white';
            ctx.beginPath();
            ctx.arc(eyeX1, eyeY1, eyeSize, 0, Math.PI * 2);
            ctx.fill();
            ctx.beginPath();
            ctx.arc(eyeX2, eyeY2, eyeSize, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制瞳孔
            ctx.fillStyle = 'black';
            ctx.beginPath();
            ctx.arc(eyeX1, eyeY1, eyeSize / 2, 0, Math.PI * 2);
            ctx.fill();
            ctx.beginPath();
            ctx.arc(eyeX2, eyeY2, eyeSize / 2, 0, Math.PI * 2);
            ctx.fill();
        }
    });
}

// 绘制食物
function drawFood() {
    ctx.fillStyle = '#FF5722';
    
    // 绘制苹果形状
    const x = food.x * GRID_SIZE + GRID_SIZE / 2;
    const y = food.y * GRID_SIZE + GRID_SIZE / 2;
    const radius = GRID_SIZE / 2 - 2;
    
    // 苹果主体
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fill();
    
    // 苹果顶部的小凹陷
    ctx.fillStyle = '#4CAF50';
    ctx.beginPath();
    ctx.arc(x, food.y * GRID_SIZE + 3, 2, 0, Math.PI * 2);
    ctx.fill();
    
    // 苹果叶子
    ctx.fillStyle = '#4CAF50';
    ctx.beginPath();
    ctx.ellipse(x + 3, food.y * GRID_SIZE + 4, 4, 2, Math.PI / 4, 0, Math.PI * 2);
    ctx.fill();
}

// 辅助函数：绘制圆角矩形
function roundRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
    ctx.fill();
}

// 暂停游戏
function togglePause() {
    if (isGameOver) return;
    
    isPaused = !isPaused;
    
    if (isPaused) {
        pauseButton.textContent = '继续';
        // 绘制暂停提示
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        ctx.font = '30px Arial';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        ctx.fillText('游戏暂停', canvas.width / 2, canvas.height / 2);
    } else {
        pauseButton.textContent = '暂停';
        draw(); // 重新绘制游戏
    }
}

// 事件监听
startButton.addEventListener('click', initGame);
pauseButton.addEventListener('click', togglePause);
restartButton.addEventListener('click', initGame);

// 键盘控制
document.addEventListener('keydown', (event) => {
    // 防止方向键滚动页面
    if ([37, 38, 39, 40].includes(event.keyCode)) {
        event.preventDefault();
    }
    
    // 如果游戏结束或暂停，不处理方向键
    if (isGameOver || isPaused) return;
    
    // 根据按键更改方向（防止180度转向）
    switch (event.keyCode) {
        case 38: // 上
            if (direction !== DIRECTIONS.DOWN) {
                nextDirection = DIRECTIONS.UP;
            }
            break;
        case 40: // 下
            if (direction !== DIRECTIONS.UP) {
                nextDirection = DIRECTIONS.DOWN;
            }
            break;
        case 37: // 左
            if (direction !== DIRECTIONS.RIGHT) {
                nextDirection = DIRECTIONS.LEFT;
            }
            break;
        case 39: // 右
            if (direction !== DIRECTIONS.LEFT) {
                nextDirection = DIRECTIONS.RIGHT;
            }
            break;
        case 32: // 空格键暂停/继续
            togglePause();
            break;
    }
});

// 移动端触摸控制
let touchStartX = 0;
let touchStartY = 0;

document.addEventListener('touchstart', (event) => {
    touchStartX = event.touches[0].clientX;
    touchStartY = event.touches[0].clientY;
});

document.addEventListener('touchmove', (event) => {
    // 防止页面滚动
    event.preventDefault();
}, { passive: false });

document.addEventListener('touchend', (event) => {
    if (isGameOver || isPaused) return;
    
    const touchEndX = event.changedTouches[0].clientX;
    const touchEndY = event.changedTouches[0].clientY;
    
    const diffX = touchEndX - touchStartX;
    const diffY = touchEndY - touchStartY;
    
    // 判断滑动方向（水平或垂直）
    if (Math.abs(diffX) > Math.abs(diffY)) {
        // 水平滑动
        if (diffX > 0 && direction !== DIRECTIONS.LEFT) {
            // 向右滑动
            nextDirection = DIRECTIONS.RIGHT;
        } else if (diffX < 0 && direction !== DIRECTIONS.RIGHT) {
            // 向左滑动
            nextDirection = DIRECTIONS.LEFT;
        }
    } else {
        // 垂直滑动
        if (diffY > 0 && direction !== DIRECTIONS.UP) {
            // 向下滑动
            nextDirection = DIRECTIONS.DOWN;
        } else if (diffY < 0 && direction !== DIRECTIONS.DOWN) {
            // 向上滑动
            nextDirection = DIRECTIONS.UP;
        }
    }
});

// 窗口大小调整时重新绘制游戏
window.addEventListener('resize', () => {
    if (!isGameOver) {
        draw();
    }
});

// 初始绘制
draw();

// 显示开始游戏提示
ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.font = '24px Arial';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('贪吃蛇游戏', canvas.width / 2, canvas.height / 2 - 50);
ctx.font = '18px Arial';
ctx.fillText('点击"开始游戏"按钮开始', canvas.width / 2, canvas.height / 2);
ctx.fillText('使用方向键控制蛇的移动', canvas.width / 2, canvas.height / 2 + 30);

// 禁用暂停按钮，直到游戏开始
pauseButton.disabled = true;